package com.umfwechat.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;

/**
 * 
 * @author WL
 *
 */
public class RedisUtil {
	
	private static Logger logger = LoggerFactory.getLogger(RedisUtil.class);
	public static final String REDIS_SPLIT = "<@-@>";
	
	/**
	 * dddd
	 * @param key
	 */
	public static void del(String key){
		Jedis jedis = JedisFactory.getJedis();
		if(null!=jedis){
			jedis.del(key); 
			logger.info("redis删除key="+key);
		}else{
			logger.error("jedis获取实例失败");
		}
		returnJedisCon(jedis);
	}
	
	/**
	 * 将key-value入redis，并为key设定存活时间
	 * @param key,time,value
	 */
	public static void set(String key,int seconds,String value){
		Jedis jedis = JedisFactory.getJedis();
		if(null!=jedis){
			jedis.setex(key, seconds, value);
			logger.info("redis放入的key="+key+",value="+jedis.get(key));
		}else{
			logger.error("jedis获取实例失败");
		}
		returnJedisCon(jedis);
	}
	public static String get(String key){
		Jedis jedis = JedisFactory.getJedis();
		String result = null;
		if(null!=jedis){
			result = jedis.get(key);
			logger.info("redis放入的key="+key+",value="+jedis.get(key));
		}else{
			logger.error("jedis获取实例失败");
		}
		returnJedisCon(jedis);
		return result;
	}
	
	/**
	 * jedis连接归还
	 * @param jedis
	 */
	private static void returnJedisCon(Jedis jedis){
		if(jedis!=null){
			jedis.close();
		}
	}
	
	public static void setObj(String key, int seconds, Object object){
		Jedis jedis = JedisFactory.getJedis();
		if(null!=jedis){
			jedis.setex(key.getBytes(), seconds, SerializeUtil.serialize(object));
			logger.info("redis放入的key="+key+",value="+jedis.get(key.getBytes()));
		}else{
			logger.error("jedis获取实例失败");
		}
		returnJedisCon(jedis);
    }
	
	public static Object getObj(String key){
		Jedis jedis = JedisFactory.getJedis();
		byte[] result = null;
		if(null!=jedis){
			result = jedis.get(key.getBytes());
			logger.info("redis放入的key="+key+",value="+jedis.get(key.getBytes()));
		}else{
			logger.error("jedis获取实例失败");
		}
		returnJedisCon(jedis);
		return SerializeUtil.unserialize(result);
    }
}
